[XPATH] Retrieve specific preceding sibling nodes attributes

Posted by Matthieu BROUILLARD on Stack Overflow See other posts from Stack Overflow or by Matthieu BROUILLARD
Published on 2010-05-26T22:15:52Z Indexed on 2010/05/26 22:21 UTC
Read the original article Hit count: 302

Filed under:
|
|

Is there an XPath way of recovering directly one specific attribute of preceding sibling nodes of an XML node using an XPath query?

In the following example, I would like to retrieve the values of the alt attribute of each img nodes that precede the div element marked with the id=marker.

<content>
  <img alt="1" src="file.gif" />
  <img alt="2" src="file.gif" />
  <img alt="3" src="file.gif" />
  <img alt="4" src="file.gif" />
  <div id='marker'></div>
</content>

For this example, I want to retrieve the values 1 2 3 4.
I use the following XPath query

//div[@id='marker']/preceding-sibling::img

in order to retrieve the node list I want

<img alt="1" src="file.gif"/>
<img alt="2" src="file.gif"/>
<img alt="3" src="file.gif"/>
<img alt="4" src="file.gif"/>

As it is a node list I can then iterate on the nodes to retrieve the attribute value I am looking for, but is there an XPath way of doing it? I would have expected to be able to write something like:

//div[@id='marker']/preceding-sibling::img@alt
or //div[@id='marker']/preceding-sibling@alt::img

but I don't even know if it is possible once you have used an XPath Axe like preceding-sibling.

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xpath